<template>
	<view>
		<view class="box">
			<!--回收员下单页面-->
			<block v-if="isHsType != 1">
				<view class="userphone">
					<view>
						<text>联系人</text>
						<input type="text" v-model="data.phone_name" disabled="true" />
					</view>
					<view>
						<text>手机号</text>
						<input type="number" v-model="data.mobile" disabled="true" />
					</view>
				</view>
				<view class="useraddress">
					<view>
						<text>定位地址</text>
						<span class="location">{{ data.location_address || '请定位地址' }}</span>
						<image class="location-icon" src="../../static/img/myhome/icon-dingwei@3x.png" mode="">
						</image>
					</view>
					<view>
						<text>详细地址</text>
						<input type="text" v-model="data.recycling_address" disabled="true" />
					</view>
				</view>
				<view class="usertime">
					<view>
						<text>预约时间</text>
						<!-- 日期 -->
						<picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
							{{ date }}
							<u-icon name="arrow-down-fill" color="#999999" size="20" class="ml30"></u-icon>
						</picker>
						<!-- 日期 -->
					</view>
					<view>
						<button @click="selectBu(item)" v-for="item in buttontiem" :key="item"
							:class="{ selectButoom: buttonseletct == item }">
							<i>{{ item }}</i>
						</button>
					</view>
				</view>
			</block>
			<!-- 用户 -->
			<block v-else>
				<view class="userphone user">
					<view class="bbn" @click="selectShow=true">
						<text>用户</text>
						<text
							:style="{ paddingLeft: '30rpx', color: selectText ? '#000' : '#CCCCCC', 'max-width':'400rpx', 'overflow': 'hidden'}">{{ selectText || '请选择用户' }}</text>
						<u-icon name="arrow-down" size="24" color="#cccccc" class="ml30"></u-icon>
					</view>
					<u-button type="primary" @click="isShowMobile=true">手机查询</u-button>
				</view>
			</block>
			<!-- 车辆 -->
			<view class="userphone user" v-if="selectText">
				<view class="bbn" @click="selectCarShow=true">
					<text>车辆</text>
					<text
						:style="{ paddingLeft: '30rpx', color: selectText ? '#000' : '#CCCCCC', 'max-width':'650rpx', 'overflow': 'hidden'}">{{ carText || '请选择车辆' }}</text>
					<u-icon name="arrow-down" size="24" color="#cccccc" class="ml30"></u-icon>
				</view>
			</view>
			<view class="textg"><text>已添加物品</text></view>
			<view class="usergoods">
				<addgood v-for="(item, index) in data.wp" :index="index" :wp="item" :key="item" @wpDelete="wpDelete"
					@showEdit="showEdit(item, index)" :datas1='indexs'></addgood>
			</view>
			<view class="add_product">
				<button @click="isShowadd_pro">
					<image src="../../static/img/myhome/add@3x.png"></image>
					<text>继续添加商品</text>
				</button>
			</view>
		</view>

		<!-- 展示继续添加商品弹窗 s -->
		<u-popup v-model="isShow" mode="bottom">
			<addprods :prevWeight="aWeight" @myEven="change" @closewin="colse" ref="popupAdd"
				:is_edit_price="is_edit_price"></addprods>
		</u-popup>
		<!-- 展示编辑商品弹窗 s -->
		<u-popup v-model="isShowEdit" mode="bottom">
			<editgood :wps="data.wp" :datas='indexe' @myEven="changeEdit" @closewin="colseEdit" ref="popupEdit">
			</editgood>
		</u-popup>

		<!-- 展示用户搜索 -->
		<u-popup v-model="isShowMobile" mode="bottom">
			<mobilequery @myEven="changeMobile" :user-list="vuserList" @closewin="colseMobile" ref="popupMobile">
			</mobilequery>
		</u-popup>
		<!-- 昵称搜索 -->
		<u-popup v-model="selectShow" mode="bottom">
			<nicknamequery @myEven="changeNickName" :user-list="vuserList" @closewin="colseNickName"
				ref="popupNickName">
			</nicknamequery>
		</u-popup>
		<!-- 车辆搜索 -->
		<u-popup v-model="selectCarShow" mode="bottom">
			<cars @selectCar="selectCar" :carList="carList" @closewin="selectCarShow=false" ref="carNickPopup">
			</cars>
		</u-popup>

		<!-- 总计金额 -->
		<view class="footer">
			<button type="default" v-if="isHsType == 1" @click="hang()">挂起</button>
			<view class="sub">
				<text>累计金额:</text>
				<span>{{ amount || 0 }}</span>
				<text>元</text>
				<button @click="post"><i>提交</i></button>
			</view>
		</view>

		<u-select v-model="selectShow" mode="single-column" label-name="nickname" value-name="id" :list="vuserList"
			@confirm="selectConfirm"></u-select>
		<!-- 支付弹窗 -->
		<u-popup v-model="popupShow" mode="center" border-radius="20">
			<view class="pay-box">
				<view class="pay-text">输入密码</view>
				<view class="pay-input">
					<view class="w100">
						<input type="number" v-model="password" maxlength="6" placeholder="请输入六位密码" password
							class="pay-input-tips" />
					</view>
				</view>
				<view class="pay-btn-box">
					<u-button type="success" size="mini" @click="sendPassword(1)" :disabled="disabledStatus"
						v-if="service_init.pay_type.indexOf('1') > -1">现金支付</u-button>
					<u-button type="success" size="mini" @click="sendPassword(2)" :disabled="disabledStatus"
						v-if="service_init.pay_type.indexOf('2') > -1">余额支付</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import Addgood from '../scan_user/Addgood1.vue';
	import addprods from '../scan_user/add_product1.vue';
	import editgood from './editgood1.vue';
	import mobilequery from '../scan_user/mobile_query1.vue';
 
	export default {
		components: {
			Addgood,
			addprods,
			editgood,
			mobilequery
		},
		data() {
			const currentDate = this.getDate({
				format: true
			});
			return {
				is_edit_price: 0,
				userInfo: null,
				date: currentDate,
				isShow: false,
				isShowEdit: false,
				isShowMobile: false,
				data: {},
				buttonseletct: '',
				buttontiem: ['08:00~10:00', '10:00~12:00', '14:00~16:00', '16:00~18:00'],
				vuserList: [],
				isHsType: 1,
				selectShow: false,
				selectText: null,
				aWeight: '',
				password: '',
				popupShow: false,
				service_init: {
					pay_type: []
				},
				indexe: null,
				indexs: null,
				carList: [],
				disabledStatus:false
			};
		},
		onLoad(options) {
			let is_hs = uni.getStorageSync('is_hs');
			console.error(options.data)
			console.log('========1====' + !this.$u.test.isEmpty(options.data))
			if (!this.$u.test.isEmpty(options.data)) {
				this.data = JSON.parse(options.data);
				let times = this.data.pickup_time_area.split(' ');
				this.date = times[0];
				this.buttonseletct = times[1];
				console.log('========2====' + is_hs)
				if (is_hs == 3) {
					// this.aWeight = this.data.wp[this.data.wp.length - 1].a_weigh
					this.selectText = this.data.nickname;
					this.data.vuid = this.data.uid;
					this.isHsType = 1;
					this._getVuser();
					uni.setNavigationBarTitle({
						title: '总仓编辑订单'
					});
				} else if (is_hs == 5) {
					// this.aWeight = this.data.wp[this.data.wp.length - 1].a_weigh
					console.log(this.data)
					this.selectText = this.data.nickname;
					this.data.vuid = this.data.uid;
					this.isHsType = 1;
					this._getVuser();
					uni.setNavigationBarTitle({
						title: '分站编辑订单'
					});
				}
			} else {
				console.log('========3====' + is_hs)
				if (is_hs == 3) {
					this.data = {
						mobile: '',
						phone_name: '',
						location_address: '',
						recycling_address: '',
						pickup_time: '',
						pickup_time_area: '',
						longitude: '',
						latitude: '',
						wp: [],
						is_virtual: 1,
						vuid: null
					};
					this.isHsType = 1;
					this._getVuser();
					uni.setNavigationBarTitle({
						title: '总仓下单'
					});
				} else if (is_hs == 5) {
					this.data = {
						mobile: '',
						phone_name: '',
						location_address: '',
						recycling_address: '',
						pickup_time: '',
						pickup_time_area: '',
						longitude: '',
						latitude: '',
						wp: [],
						is_virtual: 2,
						vuid: null
					};
					this.isHsType = 1;
					this._getVuser();
					uni.setNavigationBarTitle({
						title: '分站下单'
					});
				}
			}
			this._getInfo();
			this._getServiceInit()

		},
		computed: {
			startDate() {
				return this.getDate('start');
			},
			endDate() {
				return this.getDate('end');
			},
			// 计算累计金额
			amount() {
				let total = 0;
				if (this.$u.test.isEmpty(this.data.wp)) {
					return;
				}
				this.data.wp.forEach((item, index) => {
					if (item.total_price > 0) {
						total += Number(item.total_price);
					}
				});

				return total.toFixed(2);
			}
		},
		methods: {
			_getServiceInit() {
				this.$u.api.getServiceInit().then(res => {
					this.service_init = res
					uni.setStorageSync('service_init', res)
				})
			},
			// 用户信息api
			_getInfo() {
				this.$u.api.getInfo().then(res => {
					this.userInfo = res;
					uni.setStorageSync('is_hs', res.is_hs);
					this.$store.commit('setUserInfo', res)
					uni.setStorageSync('userInfo', res);
					this.$store.commit('setIsUserEdit', 0);
					this.is_edit_price = res.is_edit_price

				}).catch(e => {})
			},
			selectConfirm(e) {
				console.log("-----selectConfirm-----");
				this.selectText = e[0].label;
				this.data.vuid = e[0].value;
			},
			selectBu(item) {
				this.buttonseletct = item;
			},
			hang() {
				if (!this.data.re_id) this.data.re_id = this.$store.state.userInfo.id;
				var that = this
				if (this.$u.test.isEmpty(this.data.vuid)) {
					uni.showToast({
						title: '请选择用户',
						duration: 1000,
						icon: 'none'
					});
					return;
				} else if (this.$u.test.isEmpty(this.data.wp)) {
					uni.showToast({
						title: '请添加至少一项物品',
						duration: 1000,
						icon: 'none'
					});
					return;
				} else {
					uni.showModal({
						title: '提示',
						content: '是否暂时挂起',
						showCancel: true,
						success: function(res) {
							if (res.confirm) {
								that._postHangAdd(that.data);
							} else if (res.cancel) {}
						}
					});
				}
			},
			_postHangAdd(data) {
				uni.showLoading({
					title: '加载中'
				});
				this.$u.api
					.postHangScan(data)
					.then(res => {
						uni.hideLoading();
						uni.showToast({
							title: '挂起成功',
							icon: 'none'
						})
						setTimeout(function() {
							// uni.navigateBack({
							// 	delta: 1
							// });
									
							uni.redirectTo({
								url: '/homepage/Test/Home/order/hangList'
							})
							
						}, 1500)
					})
					.catch(err => {
						uni.hideLoading();
						uni.showToast({
							title: err.msg,
							duration: 1000
						});
					});
			},
			post() {
				var that = this;
				if (that.isHsType == 1) {
					if (that.$u.test.isEmpty(that.data.vuid)) {
						uni.showToast({
							title: '请选择用户',
							duration: 1000,
							icon: 'none'
						});
						return;
					} else if (that.$u.test.isEmpty(that.data.wp)) {
						uni.showToast({
							title: '请添加至少一项物品',
							duration: 1000,
							icon: 'none'
						});
						return;
					} else {
						//20221123在付款前确认回皮重量
						uni.showModal({
							title: '提示',
							content: '是否已经填写回皮重量？',
							showCancel: true,
							cancelText: '去填写',
							confirmText: '付款',
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击确定');
									that.popupShow = true;
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});

						// this.selectPayType();
						// this._postRecoverAdd(this.data);
					}
				} else {
					that._postRecoverEdit();
				}
			},
			selectPayType() {
				var that = this;
				uni.showModal({
					showCancel: true,
					title: '请选择支付方式',
					content: '支付金额：￥' + this.amount,
					cancelText: '余额支付',
					confirmText: '现金支付',
					success: (res) => {
						if (res.confirm) {
							that._postRecoverAdd(that.data);
						} else if (res.cancel) {
							that.popupShow = true;
							// this._postUserOrderPay(ids, 1);
						}
					}
				});
			},
			/*验证支付密码*/
			sendPassword(type) {
				var that = this;
				if (that.$u.test.isEmpty(that.password)) {
					uni.showToast({
						title: '请输入密码',
						duration: 1000,
						icon: 'none',
					});
					return false;
				}
				that.$u.api.checkUserPayPassword({
					'password': that.password
				}).then(res => {
					if (type == 2) {
						if (parseFloat(that.amount) > parseFloat(that.userInfo.balance)) {
							uni.showToast({
								title: '余额不足',
								duration: 1000,
								icon: 'none'
							});
							that.popupShow = false;
							that.password = '';
							return false;
						}
					}

					that.data.send_type = type
					that.disabledStatus = true
					that.popupShow = false
					
					that._postRecoverAdd(that.data);
				}).catch(err => {
					uni.showToast({
						title: err.msg,
						duration: 1000,
						icon: 'none'
					});
				})
			},
			_postRecoverEdit() {
				this.$u.api.postRecoverEdit(this.data).then(res => {
					uni.showModal({
						title: '提示',
						content: '操作成功',
						showCancel: false,
						success: res => {
							if (res.confirm) {
								uni.navigateBack({
									delta: 1
								});
								this.$store.commit('setEditOrder', 1);
							} else if (res.cancel) {}
						}
					});
				});
			},
			_postRecoverAdd(data) {
				let that = this
				uni.showLoading({
					title: '加载中'
				});
				this.$u.api
					// .postRecoverAdd(data) 
					.postRecovernAddNew(data)
					.then(res => {
						uni.hideLoading();
						that.popupShow = false;
						that.disabledStatus = false

						let msg = res ? res.msg : '下单成功'
						uni.showModal({
							title: '提示',
							content: msg,
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									uni.navigateBack({
										delta: 1
									});	
								}
							}
						});	
						// this._postComplete(res.order_id, data.send_type);
					})
					.catch(err => {
						that.disabledStatus = false
						
						uni.hideLoading();
						uni.showToast({
							title: err.msg,
							duration: 1000
						});
					});
			},
			_postComplete(id) {
				uni.showLoading({
					title: '加载中'
				});
				this.$u.api
					.postComplete({
						id: id,
						send_type: send_type
					})
					.then(res => {
						uni.hideLoading();
						// uni.showToast({
						//     title: '订单完成',
						//     duration: 1000
						// });
						uni.showModal({
							title: '提示',
							content: '下单成功',
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									uni.navigateBack({
										delta: 1
									});
								}
							}
						});
					})
					.catch(err => {
						uni.hideLoading();
						uni.showToast({
							title: err.msg,
							duration: 2000,
							icon: 'none'
						});
					});
			},
			bindDateChange: function(e) {
				this.date = e.target.value;
			},
			getDate(type) {
				const date = new Date();
				let year = date.getFullYear();
				let month = date.getMonth() + 1;
				let day = date.getDate();

				if (type === 'start') {
					year = year - 60;
				} else if (type === 'end') {
					year = year + 2;
				}
				month = month > 9 ? month : '0' + month;
				day = day > 9 ? day : '0' + day;
				return `${year}-${month}-${day}`;
			},
			// 日期 e
			// 弹窗
			isShowadd_pro() {
				this.isShow = true;
				if (this.isHsType == 1) {
					this.$refs.popupAdd.handPriceDisabled();
					this.$refs.popupAdd.prevWeight(this.aWeight);
				}
			},
			// 将子组件的数据 push 进 数组中
			change(options) {
				this.aWeight = options.a_weigh
				this.data.wp.push(options);
				this.isShow = false;
			},
			colse() {
				this.isShow = false;
			},

			showEdit(item, index) {
				if (this.isHsType == 1) {
					this.$refs.popupEdit.handPriceDisabled();
					this.$refs.popupEdit.setTypeName(item.wp_name);
					
				}
				let isGetWeight = 1; //是否获取重量，由于editgood.vue是被调用的包装元素，原来的并不传isGetWeight参数
				// this.$refs.popupEdit.cre(item, index, isGetWeight);
				this.isShowEdit = true;

				let PriceDisabled = this.is_edit_price == 1 ? false : true
				this.$refs.popupAdd.setPriceDisabled(PriceDisabled);
				this.indexe = index
				this.indexs = index

			},
			wpDelete(index) {
				this.$u.api.postRecoverDel({
					id: this.data.wp[index].id
				});
				this.data.wp.splice(index, 1);
				this.aWeight = this.data.wp[this.data.wp.length - 1].a_weigh
			},
			// 重新编辑订单，修改订单
			changeEdit(data) {

				this.$set(this.data.wp, data.datas, data.wpp)
				// this.data.wp[data.datas] = data.wpp;
				this.isShowEdit = false;
			},
			// 将子组件的数据 push 进 数组中
			changeEditold(params) {
				//console.log("----------------changeEdit");
				//console.log(params.wp);
				//console.log(params.index);
				let index = params.index;
				let item = params.wp;
				//计算过磅前后重数，价线
				//console.log("----------------a_weigh");
				//console.log(item.a_weigh);
				//console.log("----------------b_weigh");
				//console.log(item.b_weigh);
				let aWeigh = Number(item.a_weigh) ? Number(item.a_weigh) : 0;
				let bWeigh = Number(item.b_weigh) ? Number(item.b_weigh) : 0;
				let rWeigh = Number(item.r_weigh) ? Number(item.r_weigh) : 0;
				//console.log(aWeigh);
				//console.log(bWeigh);
				if (bWeigh > aWeigh) {
					let tWeight = bWeigh - aWeigh - rWeigh;
					item.nums = tWeight;
					//item.weight = tWeight;
					item.total_price = item.nums * item.unit_price;
					item.total_price = item.total_price.toFixed(2);
				}
				//如果有多种货物，就把上一次卸货后的重量赋给下一个货物的过磅前重量
				if ((aWeigh > 0) && (this.data.wp.length - index > 1)) {
					this.data.wp[index + 1].b_weigh = item.a_weigh;
				}

				this.data.wp[index] = item;
				this.isShowEdit = false;
				//console.log("---------this.data.wp---------");
				//console.log(this.data.wp);
			},
			colseEdit() {
				this.isShowEdit = false;
			},
			colseMobile() {
				this.isShowMobile = false;
			},
			changeMobile(item, index) {
				this.selectText = item.nickname;
				this.data.vuid = item.id;
				this.isShowMobile = false
			},
			_getVuser() {
				this.$u.api.getVuser().then(res => {
					this.vuserList = res;
				});
			}
		}
	};
</script>
<style lang="scss" scoped>
	.ml30 {
		margin-left: 30rpx;
	}

	.bbn {
		border-bottom: none;
	}

	.user {
		height: unset;
		display: flex;
		align-items: center;
		padding: 10rpx;
	}

	.location {
		width: 400rpx;
		text-overflow: ellipsis;
		overflow: hidden;
		white-space: nowrap;
	}

	.location-icon {
		margin-top: 0;
	}

	.w100 {
		width: 100%;
	}

	.pay-box {
		padding: 50rpx;
		width: 500rpx;
	}

	.pay-text {
		font-size: 35rpx;
		font-weight: bold;
		text-align: center;
	}

	.pay-input {
		display: flex;
		font-size: 30rpx;
		padding: 50rpx 0;
	}

	.pay-input-tips {
		border-bottom: 1rpx solid #999999;
	}

	.pay-btn-box {
		display: flex;
		justify-content: space-around;
	}

	.pay_btn {
		background-color: #18B566;
		color: #FFFFFF;
		height: 75rpx;
		line-height: 75rpx;
	}

	.cover_view {
		height: 300rpx;
		background-color: pink;
	}

	.box {
		padding: 30rpx;
		// background-color: #eee;
		// min-height: 1500rpx;
	}

	.textg {
		font-size: 32rpx;
		line-height: 38rpx;
		color: #2d3945;
		margin: 60rpx 0 30rpx 30rpx;
	}

	span {
		font-size: 28rpx;
		line-height: 48rpx;
		color: #666666;
		margin-left: 30rpx;
	}

	.userphone {
		background-color: #ffffff;
		border-radius: 20rpx;
		padding-left: 30rpx;
		line-height: 98rpx;
		margin-bottom: 30rpx;

		button {
			background-color: #2b85e4;
			color: #ffffff;
			transform: scale(0.8);
		}

		view:nth-child(1) {
			border-bottom: 1px solid #eeeeee;
			flex-grow: 1;
		}

		view {
			display: flex;
			align-items: center;

			input {
				padding-left: 30rpx;
			}
		}
	}

	.useraddress {
		height: 196rpx;
		background-color: #ffffff;
		border-radius: 20rpx;
		padding: 0 30rpx;
		line-height: 98rpx;
		margin-bottom: 30rpx;

		view:nth-child(1) {
			border-bottom: 1px solid #eeeeee;
		}

		view {
			display: flex;
			align-items: center;

			input {
				padding-left: 30rpx;
			}
		}

		image {
			float: right;
			margin-top: 30rpx;
			width: 50rpx;
			height: 50rpx;
		}
	}

	.usertime {
		height: 308rpx;
		background-color: #ffffff;
		border-radius: 20rpx;
		padding: 0 30rpx;
		line-height: 98rpx;
		margin-bottom: 30rpx;

		picker {
			font-size: 28rpx;
			color: #666666;
			text-align: left;
			margin-left: 30rpx;
			flex: 1;
		}

		view:nth-child(1) {
			border-bottom: 1px solid #eeeeee;
			display: flex;
		}

		view:nth-child(2) {
			margin-top: 30rpx;
			display: flex;
			flex-wrap: wrap;
		}

		button {
			width: 190rpx;
			height: 70rpx;
			border-radius: 35rpx;
			background-color: #ffffff;
			border: solid 2rpx #f2f2f2;
			margin: 0 10rpx 10rpx 0;
		}

		i {
			font-size: 24rpx;
			line-height: 70rpx;
			color: #999999;
		}

		.selectButoom {
			background-color: #1bc078;
			// color: #ffffff;

			i {
				color: #ffffff;
			}
		}
	}

	.add_product {
		margin-bottom: 10vh;

		button {
			width: 570rpx;
			height: 98rpx;
			line-height: 98rpx;
			background-color: #ffffff;
			border-radius: 49rpx;
		}

		text {
			font-size: 28rpx;
			color: #1bc078;
		}

		image {
			margin-right: 20rpx;
			width: 24rpx;
			height: 24rpx;
		}
	}

	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		padding: 10rpx 30rpx;
		background-color: #ffffff;
		padding-bottom: env(safe-area-inset-bottom);
		display: flex;
		flex-direction: column;

		text {
			font-size: 32rpx;
			color: #191919;
		}

		span {
			font-size: 32rpx;
			color: #ff4200;
			margin: 0 28rpx;
		}

		>button {
			position: absolute;
			left: 2%;
			top: -100%;
			border-radius: 999rpx;
			background-color: #f0ad4e;
			color: #fff;
			padding: 20rpx 30rpx;
		}

		.sub {
			display: flex;
			justify-content: space-around;
			align-items: center;
			margin-top: 5rpx;

			button {
				width: 262rpx;
				height: 78rpx;
				background-color: #1bc078;
				border-radius: 39rpx;
				margin: 0;

				i {
					font-size: 32rpx;
					color: #ffffff;
				}
			}
		}
	}

	.showeditgood {
		height: 100%;
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		z-index: 998;
	}
</style>